// 全局变量
let currentEmployee = null;
let mediaRecorder = null;
let audioChunks = [];
let audioBlob = null;

// API 基础URL
const API_BASE = '';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    checkLoginStatus();
    setupEventListeners();
    loadManualContent();
});

// 设置事件监听器
function setupEventListeners() {
    // 登录/注册按钮
    document.getElementById('loginBtn').addEventListener('click', showAuthModal);
    document.getElementById('logoutBtn').addEventListener('click', logout);
    document.getElementById('authForm').addEventListener('submit', handleLogin);
    document.getElementById('registerBtn').addEventListener('click', handleRegister);

    // 功能按钮
    document.getElementById('generateVoiceBtn').addEventListener('click', showEmployeeArea);
    document.getElementById('viewManualBtn').addEventListener('click', showManualModal);

    // 录音按钮
    document.getElementById('startRecording').addEventListener('click', startRecording);
    document.getElementById('stopRecording').addEventListener('click', stopRecording);

    // 二维码分享
    document.getElementById('copyQrBtn').addEventListener('click', copyQRCode);
    document.getElementById('shareWechatBtn').addEventListener('click', shareToWechat);

    // 模态框关闭
    document.getElementById('closeManualBtn').addEventListener('click', closeManualModal);
    
    // 点击模态框外部关闭
    document.getElementById('authModal').addEventListener('click', function(e) {
        if (e.target === this) hideAuthModal();
    });
    document.getElementById('manualModal').addEventListener('click', function(e) {
        if (e.target === this) closeManualModal();
    });
}

// 检查登录状态
function checkLoginStatus() {
    const employee = localStorage.getItem('currentEmployee');
    if (employee) {
        currentEmployee = JSON.parse(employee);
        showUserInfo();
    }
}

// 显示用户信息
function showUserInfo() {
    document.getElementById('loginBtn').classList.add('hidden');
    document.getElementById('userInfo').classList.remove('hidden');
    document.getElementById('userName').textContent = currentEmployee.name || currentEmployee.phone;
}

// 显示认证模态框
function showAuthModal() {
    document.getElementById('authModal').classList.remove('hidden');
    document.getElementById('authModal').classList.add('flex');
}

// 隐藏认证模态框
function hideAuthModal() {
    document.getElementById('authModal').classList.add('hidden');
    document.getElementById('authModal').classList.remove('flex');
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const phone = document.getElementById('phone').value;
    const password = document.getElementById('password').value;
    
    try {
        const response = await fetch(`${API_BASE}/api/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ phone, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentEmployee = data.employee;
            localStorage.setItem('currentEmployee', JSON.stringify(currentEmployee));
            showUserInfo();
            hideAuthModal();
            showEmployeeArea();
            loadInteractionStats();
            loadFamilyMessages();
        } else {
            alert(data.error || '登录失败');
        }
    } catch (error) {
        alert('网络错误，请重试');
    }
}

// 处理注册
async function handleRegister() {
    const phone = document.getElementById('phone').value;
    const password = document.getElementById('password').value;
    const name = document.getElementById('name').value;
    
    if (!phone || !password) {
        alert('请填写手机号和密码');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/api/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ phone, password, name })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('注册成功，请登录');
            document.getElementById('authForm').reset();
        } else {
            alert(data.error || '注册失败');
        }
    } catch (error) {
        alert('网络错误，请重试');
    }
}

// 退出登录
function logout() {
    currentEmployee = null;
    localStorage.removeItem('currentEmployee');
    document.getElementById('loginBtn').classList.remove('hidden');
    document.getElementById('userInfo').classList.add('hidden');
    document.getElementById('employeeArea').classList.add('hidden');
}

// 显示员工区域
function showEmployeeArea() {
    if (!currentEmployee) {
        showAuthModal();
        return;
    }
    
    document.getElementById('employeeArea').classList.remove('hidden');
    loadInteractionStats();
    loadFamilyMessages();
}

// 开始录音
async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        
        mediaRecorder = new MediaRecorder(stream);
        audioChunks = [];
        
        mediaRecorder.ondataavailable = function(event) {
            audioChunks.push(event.data);
        };
        
        mediaRecorder.onstop = function() {
            audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            uploadVoice();
        };
        
        mediaRecorder.start();
        
        document.getElementById('startRecording').classList.add('hidden');
        document.getElementById('stopRecording').classList.remove('hidden');
        document.getElementById('recordingStatus').textContent = '正在录音...';
        document.getElementById('recordingStatus').classList.add('recording-animation');
        
    } catch (error) {
        alert('无法访问麦克风，请检查权限设置');
    }
}

// 停止录音
function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
        mediaRecorder.stream.getTracks().forEach(track => track.stop());
        
        document.getElementById('startRecording').classList.remove('hidden');
        document.getElementById('stopRecording').classList.add('hidden');
        document.getElementById('recordingStatus').textContent = '录音完成，正在上传...';
        document.getElementById('recordingStatus').classList.remove('recording-animation');
    }
}

// 上传语音
async function uploadVoice() {
    if (!audioBlob) return;
    
    const formData = new FormData();
    formData.append('voice', audioBlob, 'voice.wav');
    formData.append('employeeId', currentEmployee.id);
    
    try {
        const response = await fetch(`${API_BASE}/api/upload-employee-voice`, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            document.getElementById('recordingStatus').textContent = '上传成功！';
            document.getElementById('qrCode').src = `${API_BASE}/${data.qrCode}`;
            document.getElementById('qrDisplayArea').classList.remove('hidden');
            loadInteractionStats();
        } else {
            alert('上传失败，请重试');
        }
    } catch (error) {
        alert('网络错误，请重试');
    }
}

// 复制二维码
function copyQRCode() {
    const qrUrl = document.getElementById('qrCode').src;
    navigator.clipboard.writeText(window.location.origin + '/' + qrUrl)
        .then(() => alert('二维码链接已复制到剪贴板'))
        .catch(() => alert('复制失败，请手动复制'));
}

// 分享到微信
function shareToWechat() {
    const qrUrl = document.getElementById('qrCode').src;
    const shareUrl = window.location.origin + '/' + qrUrl;
    
    // 创建临时输入框
    const input = document.createElement('input');
    input.value = shareUrl;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    
    alert('链接已复制，请在微信中粘贴分享给家人');
}

// 加载互动统计
async function loadInteractionStats() {
    if (!currentEmployee) return;
    
    try {
        const response = await fetch(`${API_BASE}/api/interaction-stats/${currentEmployee.id}`);
        const data = await response.json();
        
        const stats = data.stats;
        document.getElementById('employeeVoiceCount').textContent = stats.employee_voice_count || 0;
        document.getElementById('familyVoiceCount').textContent = stats.family_voice_count || 0;
        document.getElementById('familyPhotoCount').textContent = stats.family_photo_count || 0;
    } catch (error) {
        console.error('加载统计失败:', error);
    }
}

// 加载家人消息
async function loadFamilyMessages() {
    if (!currentEmployee) return;
    
    try {
        const response = await fetch(`${API_BASE}/api/employee-messages/${currentEmployee.id}`);
        const data = await response.json();
        
        const container = document.getElementById('familyMessages');
        container.innerHTML = '';
        
        data.messages.forEach(message => {
            if (message.sender_type === 'family') {
                const messageDiv = createMessageCard(message);
                container.appendChild(messageDiv);
            }
        });
        
        if (data.messages.filter(m => m.sender_type === 'family').length === 0) {
            container.innerHTML = '<p class="text-gray-500 text-center">暂无家人的安全叮嘱</p>';
        }
    } catch (error) {
        console.error('加载消息失败:', error);
    }
}

// 创建消息卡片
function createMessageCard(message) {
    const card = document.createElement('div');
    card.className = 'message-card bg-gray-50 rounded-lg p-4';
    
    let content = '';
    
    if (message.audio_path) {
        content += `
            <div class="mb-2">
                <audio controls class="audio-player">
                    <source src="${API_BASE}/${message.audio_path}" type="audio/wav">
                    您的浏览器不支持音频播放
                </audio>
            </div>
        `;
    }
    
    if (message.photo_path) {
        content += `
            <div class="mb-2">
                <img src="${API_BASE}/${message.photo_path}" alt="家人照片" class="max-w-full h-auto rounded">
            </div>
        `;
    }
    
    const date = new Date(message.created_at).toLocaleString('zh-CN');
    
    card.innerHTML = `
        <div class="flex justify-between items-start mb-2">
            <span class="text-sm text-gray-600">来自家人的安全叮嘱</span>
            <span class="text-xs text-gray-500">${date}</span>
        </div>
        ${content}
    `;
    
    return card;
}

// 显示安全手册模态框
function showManualModal() {
    document.getElementById('manualModal').classList.remove('hidden');
    document.getElementById('manualModal').classList.add('flex');
}

// 关闭安全手册模态框
function closeManualModal() {
    document.getElementById('manualModal').classList.add('hidden');
    document.getElementById('manualModal').classList.remove('flex');
}

// 加载安全手册内容
function loadManualContent() {
    const manualContent = `
        <div class="manual-section">
            <h4>煤矿井下电气作业安全操作指南</h4>
            <ul>
                <li>严格执行停送电制度，做到"谁停电、谁送电"</li>
                <li>检修前必须验电、放电、挂接地线</li>
                <li>严禁带电作业，特殊情况必须制定安全措施</li>
                <li>定期检查电气设备防爆性能</li>
                <li>保持电气设备清洁干燥，防止漏电</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿井下爆破作业安全操作指南</h4>
            <ul>
                <li>严格执行"一炮三检"制度</li>
                <li>爆破工必须持证上岗</li>
                <li>爆破材料必须分箱存放，严禁混放</li>
                <li>爆破前必须设置警戒，清点人数</li>
                <li>处理拒爆、残爆时必须按规程操作</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿安全检查作业安全操作指南</h4>
            <ul>
                <li>入井前必须检查仪器仪表完好性</li>
                <li>严格按照检查路线进行检查</li>
                <li>发现隐患立即处理或上报</li>
                <li>做好检查记录，签字确认</li>
                <li>严禁走过场、假检查</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿提升机操作作业安全操作指南</h4>
            <ul>
                <li>操作前必须进行设备检查</li>
                <li>严格执行信号规定，确认无误后方可开车</li>
                <li>运行中注意观察仪表和信号</li>
                <li>发现异常立即停车检查</li>
                <li>严禁超载运行</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿探放水作业安全操作指南</h4>
            <ul>
                <li>严格执行"预测预报、有疑必探、先探后掘"原则</li>
                <li>探放水前必须加固工作面支护</li>
                <li>安装好排水系统，确保排水能力</li>
                <li>探放水时必须有专人监视</li>
                <li>发现异常立即停止作业</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿瓦斯检查作业安全操作指南</h4>
            <ul>
                <li>瓦斯检查员必须持证上岗</li>
                <li>严格按照规定时间、地点进行检查</li>
                <li>检查数据必须真实准确</li>
                <li>发现瓦斯超限立即停止作业</li>
                <li>做好检查记录并签字</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿瓦斯抽采作业安全操作指南</h4>
            <ul>
                <li>抽采系统必须完好可靠</li>
                <li>定期检查抽采效果</li>
                <li>抽采管路必须吊挂平直</li>
                <li>抽采钻场必须设置栅栏和警示牌</li>
                <li>抽采数据必须真实记录</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿防突作业安全操作指南</h4>
            <ul>
                <li>严格执行区域和局部综合防突措施</li>
                <li>防突预测预报必须准确</li>
                <li>防突措施效果检验必须合格</li>
                <li>安全防护设施必须完好</li>
                <li>发现突出预兆立即撤人</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿安全监测监控作业安全操作指南</h4>
            <ul>
                <li>监控系统必须24小时连续运行</li>
                <li>传感器设置必须符合规定</li>
                <li>定期调校传感器，确保数据准确</li>
                <li>发现异常立即汇报处理</li>
                <li>严禁随意更改报警值</li>
            </ul>
        </div>

        <div class="manual-section">
            <h4>煤矿采煤机（掘进机）操作作业安全操作指南</h4>
            <ul>
                <li>操作前必须检查设备各部件</li>
                <li>严格执行开机信号制度</li>
                <li>操作时注意观察周围环境</li>
                <li>发现异常立即停机处理</li>
                <li>严禁设备带病运行</li>
            </ul>
        </div>
    `;
    
    document.getElementById('manualContent').innerHTML = manualContent;
}

// 定期刷新数据
setInterval(() => {
    if (currentEmployee) {
        loadInteractionStats();
        loadFamilyMessages();
    }
}, 30000); // 每30秒刷新一次
